package com.shared.util;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.joda.time.DateTime;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.rsa.crypto.KeyStoreKeyFactory;

import java.security.KeyPair;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtils {
    public static String createToken(Date expireDate, Map claims) {
        return Jwts.builder()
                .setIssuedAt(new Date())
                .setClaims(claims)  //自定义数据
                .setExpiration(expireDate)
                .setHeaderParam("typ", "JWT")
                .signWith(getKeyPair().getPrivate(), SignatureAlgorithm.RS256)  //指定加密算法及秘钥
                .compact();
    }

    public static KeyPair getKeyPair() {
        //加载秘钥库文件
        ClassPathResource resource = new ClassPathResource("keykey.jks");
        //参数2是访问秘钥库的密码
        KeyStoreKeyFactory factory = new KeyStoreKeyFactory(resource, "keykey".toCharArray());
        return factory.getKeyPair("keykey", "keykey".toCharArray());
    }

    public static Map parseToken(String token) {
        return Jwts.parserBuilder().setSigningKey(getKeyPair().getPublic()).build().parseClaimsJws(token).getBody();
    }
}
